package com.syh.jn.scm.infrastructure.repository.impl.supplier.finance;

import cn.redscarf.commons.wrapper.Wrapper;
import com.syh.core.ddd.infrastructure.repository.AbstractAggregateRepository;
import com.syh.jn.scm.domain.supplier.entity.finance.PaymentBill;
import com.syh.jn.scm.domain.supplier.repository.finance.PaymentBillRepository;
import com.syh.jn.scm.dto.supplier.finance.PaymentBillVo;
import com.syh.jn.scm.infrastructure.repository.model.finance.PaymentBillModel;
import com.syh.jn.scm.infrastructure.repository.utils.SQLAliasGenerateUtil;
import com.syh.jn.scm.infrastructure.wrapper.BaseResolve;
import com.syh.jn.scm.infrastructure.wrapper.ResolveToSQL;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;

@Repository
public class PaymentBillRepositoryImpl extends AbstractAggregateRepository<PaymentBill, PaymentBillModel, Long> implements PaymentBillRepository {

  @Override
  protected BaseResolve getViewWrapperResolve(Wrapper wrapper) {
    Map<String,String> map = new HashMap<>();
    map.put("id","paymentBill.ID");
    map.put("receiptState","paymentBill.RECEIPT_STATE");
    map.put("code","paymentBill.CODE");
    map.put("customerType","paymentBill.CUSTOMER_TYPE");
    map.put("customerId","paymentBill.CUSTOMER_ID");
    map.put("statementOfAccountId","paymentBill.STATEMENT_OF_ACCOUNT_ID");
    map.put("statementOfAccountCode","statementAccount.CODE");
    map.put("inputTimestamp","paymentBill.INPUT_TIMESTAMP");
    map.put("businessEntityId", "paymentBill.BUSINESS_ENTITY_ID");
    ResolveToSQL parse = new ResolveToSQL(wrapper, (propertyName) -> {
      return map.get(propertyName);
    });
    return parse;
  }

  @Override
  protected SQL getViewSql() {
    return new SQL(){{
      SELECT(SQLAliasGenerateUtil.aliasGenerate(PaymentBillModel.class, "paymentBill", null),
              "statementAccount.CODE AS statementOfAccountCode",
              "CONCAT(IFNULL(downstream.`NAME`,''), IFNULL(logistics.`NAME`,''),  IFNULL(upstream.`NAME`, ''))AS customerName");
      FROM("T_FINANCE_PAYMENT_BILL AS paymentBill");
      LEFT_OUTER_JOIN("T_BASE_DOWNSTREAM AS downstream ON paymentBill.CUSTOMER_ID = downstream.ID AND paymentBill.CUSTOMER_TYPE = 1");
      LEFT_OUTER_JOIN("T_BASE_UPSTREAM AS upstream ON paymentBill.CUSTOMER_ID = upstream.ID AND paymentBill.CUSTOMER_TYPE = 0");
      LEFT_OUTER_JOIN("T_BASE_LOGISTICS AS logistics ON (logistics.ID = paymentBill.CUSTOMER_ID AND paymentBill.CUSTOMER_TYPE = 2)");
      LEFT_OUTER_JOIN("T_FINANCE_STATEMENT_ACCOUNT_BILL statementAccount ON statementAccount.id = paymentBill.STATEMENT_OF_ACCOUNT_ID ");
    }};
  }

  @Override
  protected Class getViewObject() {
    return PaymentBillVo.class;
  }

}
